package com.xjtu.platform.security.updateInfo;

import com.xjtu.platform.common.CommonService;
import com.xjtu.platform.common.CurrentUser;
import com.xjtu.platform.common.Result;
import com.xjtu.platform.common.TokenUtils;
import com.xjtu.platform.security.emailConfirm.EmailConfirmAPI;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;

@RestController
@RequestMapping("/security/updateInfo")
public class UpdateInfoAPI {
    @Resource
    private CommonService commonService;

    @Resource
    private UpdateInfoService updateInfoService;

    @PostMapping("")
    public Result updateInfo(@RequestBody UpdateInfoDto updateInfoDto, @RequestHeader("Token") String token){
        String user_id = getCurrentUserIdByToken(token);
        int flag = updateInfoService.getFlag(user_id);
        long currentTime = System.currentTimeMillis();
//        System.out.println(currentTime);
        long cachetime = updateInfoService.getCachetime(user_id);
        if(currentTime - cachetime <= 600000) {
            if (flag == updateInfoDto.getUserCode()) {
                boolean ok = updateInfoService.updateInfo(updateInfoDto, user_id);
                if (ok) {
                    return Result.success("修改成功");
                } else {
                    return Result.fail(Result.ERR_CODE_SYS, "系统维护中......");
                }
            } else {
                return Result.fail(Result.ERR_CODE_BUSINESS, "验证码错误");
            }
        }else{
            return Result.fail(Result.ERR_CODE_SYS, "验证码时间超过10分钟");
        }
    }

    @GetMapping("/getUserInfo")
    public Result getUserInfo(@RequestHeader("Token") String token){
        String user_id = getCurrentUserIdByToken(token);
        UserDto dto = new UserDto();
        Map<String,Object> page = updateInfoService.getUserInfo(user_id,dto);

        return Result.success(page);
    }

    public String getCurrentUserIdByToken(String token)
    {
        CurrentUser currentUser = TokenUtils.getUserInfo(token,commonService);
        System.out.println(currentUser);
        return currentUser.getUserId();
    }

}
